<template>
  <BasicDrawer :title="drawerTitle" v-bind="$attrs" width="500px" @register="register" destroyOnClose showFooter @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer'
  import { useForm, BasicForm } from '/@/components/Form'
  import { ref } from 'vue'

  import { formSchemas } from './ConfigActivity.data'

  // Emits声明
  const emit = defineEmits(['register', 'success'])

  const drawerTitle = ref<string>('')
  const isUpdate = ref<boolean>(false)

  const [register, { closeDrawer, setDrawerProps }] = useDrawerInner(async (data) => {
    console.log('useDrawerInner', data)
    if (data.record.id) {
      isUpdate.value = true
      drawerTitle.value = '编辑节点【' + data.record.name + ']'
    } else {
      isUpdate.value = false
      drawerTitle.value = '新增节点'
    }
    await resetFields()

    await setFieldsValue({
      ...data.record,
    })
  })

  /**
   * BasicForm绑定注册;
   * useForm 是整个框架的核心用于表单渲染，里边封装了很多公共方法;
   * 支持（schemas: 渲染表单列，autoSubmitOnEnter：回车提交,submitButtonOptions：自定义按钮文本和图标等方法）；
   * 平台通过此封装，简化了代码，支持自定义扩展;
   */
  const [registerForm, { resetFields, validate, setFieldsValue }] = useForm({
    //注册表单列
    schemas: formSchemas,
    //回车提交
    autoSubmitOnEnter: false,
    //不显示重置按钮
    showResetButton: false,
    showSubmitButton: true,
    //查询列占比 24代表一行 取值范围 0-24
    actionColOptions: { span: 17 },
  })

  /**
   * 点击提交按钮的value值
   */
  async function handleSubmit() {
    try {
      let values = await validate()
      console.log('提交按钮数据::::', values)
      setDrawerProps({ confirmLoading: true })

      //关闭弹窗
      closeDrawer()
      //刷新列表
      emit('success', { isUpdate, values })
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
